import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JTextField;
import javax.swing.Timer;

public class Controller 
{
	private LEDController lc;
	private AccelerometerController ac;
	private PillarController pc;
	private State state;
	private int gameTime;
	private JTextField textField;
	private SoundPlayer sp;
	private Timer gameTimer;
	
	public Controller(State state, int timeChange, int gameTime, JTextField textField)
	{
		this.state = state;
		this.textField = textField;
		this.gameTime = gameTime*60000;
		lc = new LEDController(state);
		pc = new PillarController(state, lc, timeChange, textField);
		ac = new AccelerometerController(state, pc);
		sp = new SoundPlayer();
	}
	
	public void startGame()
	{
		if (state.getIsRunning()==false)
		{
		state.setIsRunning(true);
		gameTimer = new Timer(gameTime, pillarAction());
		gameTimer.start();
		ac.startProgram();
		lc.startProgram();
		sp.play("40754__tommon__One_Blast_Whistle.mp3");
		pc.run();
		}
	}
	
	public void stopGame()
	{
		state.setIsRunning(false);
		gameTimer.stop();
		sp.play("40754__tommon__One_Blast_Whistle.mp3");
		pc.endProgram();
		ac.endProgram();
		lc.endProgram();
		state.setLastGameScore(state.getScore());
		state.setScore(0);
	}
	
	public Action pillarAction()
	{
		return new AbstractAction()
		{
			public void actionPerformed(ActionEvent e)
			{
				textField.setText("Final score: " + Integer.toString(state.getScore()));
				stopGame();
			}
		};
	}
}
